Component({
  data: {
    selected: 0,
    color: "#999999",
    selectedColor: "#4CAF50",
    list: [
      {
        pagePath: "/pages/health/health",
        text: "健康",
        icon: "🩺"
      },
      {
        pagePath: "/pages/diet/diet",
        text: "饮食",
        icon: "🍽️"
      },
      {
        pagePath: "/pages/exercise/exercise",
        text: "运动",
        icon: "🤸"
      },
      {
        pagePath: "/pages/profile/profile",
        text: "我的",
        icon: "👨‍⚕️"
      }
    ]
  },
  attached() {
    // 初始化时确定当前页面
    try {
      const pages = getCurrentPages();
      if (pages.length) {
        const currentPage = pages[pages.length - 1];
        const route = currentPage.route || '';
        const fullPath = `/${route}`;
        
        // 打印调试信息
        console.log("当前路径:", fullPath);
        console.log("TabBar页面列表:", this.data.list.map(item => item.pagePath));
        
        // 查找匹配的索引
        const index = this.data.list.findIndex(item => 
          fullPath === item.pagePath
        );
        
        // 如果找到匹配项，更新选中状态
        if (index !== -1) {
          console.log("找到匹配项，索引:", index);
          this.setData({ selected: index });
        } else {
          console.log("未找到匹配项，保持默认索引: 0");
        }
      }
    } catch (error) {
      console.error("TabBar初始化错误:", error);
    }
  },
  methods: {
    switchTab(e) {
      const data = e.currentTarget.dataset;
      const url = data.path;
      
      // 先执行选中效果动画
      this.setData({
        selected: data.index
      });
      
      // 再跳转到对应页面
      wx.switchTab({ url });
    },
    
    // 获取当前页面在tabBar中的索引
    getTabBarIndex() {
      try {
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        const currentRoute = `/${currentPage.route}`;
        
        // 找到当前页面对应的 tabBar 项
        const tabBarIndex = this.data.list.findIndex(item => 
          currentRoute === item.pagePath
        );
        
        return tabBarIndex !== -1 ? tabBarIndex : 0;
      } catch (error) {
        console.error("获取TabBar索引错误:", error);
        return 0;
      }
    }
  }
}); 